package cn.felord.autoconfigure;

import cn.felord.oss.Storage;
import cn.felord.oss.TencentStorage;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * The type tencent oss configuration.
 *
 * @author felord.cn
 * @since 2020 /8/24 19:42
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(COSClient.class)
class TencentCosConfiguration {


    /**
     * tencent storage storage.
     *
     * @param ossProperties the oss properties
     * @return the storage
     */
    @Bean
    @Qualifier("tencentStorage")
    Storage tencentStorage(OSSProperties ossProperties) {
        Map<String, COSClient> cosClientMap = ossProperties.getTencent().stream()
                .filter(OSSProperties.Tencent::isActive)
                .collect(Collectors.toMap(OSSProperties.Tencent::getBucketName,
                        tencent -> {
                            BasicCOSCredentials cosCredentials = new BasicCOSCredentials(tencent.getAccessKey(), tencent.getSecretKey());
                            ClientConfig clientConfig = new ClientConfig();
                            clientConfig.setRegion(new Region(tencent.getRegion()));
                            return new COSClient(cosCredentials, clientConfig);
                        }));
        return new TencentStorage(cosClientMap);
    }


}
